import router from './router'
import store from './store'
import { Message } from 'element-ui';

router.beforeEach(async(to, from, next) => {
    const Token = sessionStorage.getItem('Token')
    if (Token) {
        if (to.path === '/login') {
            next()
        } else {
            if (!store.state.user.userId) {
                // store.dispatch('setRole').then(res => {
                //     console.log(res)
                //     store.dispatch('GenerateRoutes', {
                //         roles: ['admin']
                //     }).then(accessRoutes => {
                //         console.log(accessRoutes,'看看accessRoutes')
                //         router.addRoutes(accessRoutes)
                //         next({
                //             ...to,
                //             replace: true
                //         })
                //     })
                // })
                next()

            } else {
                if (to.matched.length === 0) {  //如果未匹配到路由
                    Message({
                        message: '请联系管理员，检查是否具有页面权限！',
                        type: 'error',
                        duration: 2 * 1000
                    })
                    from.path ? next({ path: from.path }) : next('/');   //如果上级也未匹配到路由则跳转主页面，如果上级能匹配到则转上级路由
                } else {
                    next();    //如果匹配到正确跳转
                }
            }
        }

    } else {
        if (to.path === '/login') {
            next()
        } else {
            next('login')
        }
    }
})